package com.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dao.Archive;
import com.dao.Users;
import com.pojo.Archivepojo;
import com.pojo.Filepojo;
import com.pojo.Logpojo;
import com.pojo.Userspojo;
import com.service.ArchiveService;
import com.service.FileService;
import com.service.LogdaoService;
import com.service.UsersService;
import com.util.MySqlSessionFactory;

@Controller
public class UsersContrller {
	UsersService ps = new UsersService();
	ArchiveService ls = new ArchiveService();
	LogdaoService gs = new LogdaoService();
	FileService fs = new FileService();

	// 用户登陆
	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	@ResponseBody
	public String login(
			@RequestParam(value = "account", defaultValue = "") String account,
			@RequestParam(value = "password", defaultValue = "") String password,
			HttpServletResponse response) {
		Userspojo userspojo = ps.queryone(account, password);
		if ("0".equals(userspojo.getCounter())) {
			return "ERR";
		}
		gs.add(userspojo.getId(), "登陆", "2012-02-02", "0");
		response.addCookie(new Cookie("user", userspojo.getId()));
		return "OK";
	}

	// 添加档案
	@RequestMapping(value = "/add.action", method = RequestMethod.POST)
	@ResponseBody
	public String add(
			@CookieValue(value = "user", defaultValue = "") String id,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "brithday", defaultValue = "") String brithday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		ls.add(archive_id, identity, name, gender, brithday, date_retire1,
				date_retire2, sp, fc, title, seniority);
		gs.add(id, "添加信息", "2012-01-01", archive_id);

		return "OK";
	}

	// 通过search查询一条档案
	@RequestMapping(value = "/queryone.action", method = RequestMethod.POST)
	@ResponseBody
	public String queryone(
			@RequestParam(value = "search", defaultValue = "") String search,
			HttpServletResponse response) {
		List<Archivepojo> map = ls.queryone(search);
		if (0 == map.size()) {
			return "ERR";
		} else if (1 < map.size()) {
			return "ERR2";
		}
		return String.valueOf(map.get(0).getId());
	}

	// 模糊查询
	@RequestMapping(value = "/query.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> query(
			@RequestParam(value = "id", defaultValue = "") String id) {
		List<Map<String, Object>> map = ls.query(id);
		gs.add(id, "浏览信息", "2012-01-01", "1");
		return map;
	}

	// 修改
	@RequestMapping(value = "/update.action", method = RequestMethod.POST)
	@ResponseBody
	public String update(
			@CookieValue(value = "user", defaultValue = "") String userid,
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "brithday", defaultValue = "") String brithday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		ls.update(id, name, gender, brithday, date_retire1, date_retire2, sp,
				fc, title, seniority);
		gs.add(id, "修改", "2013-03-03", archive_id);
		return "OK";
	}

	// 查询用户昵称
	@RequestMapping(value = "/queryUsers.action", method = RequestMethod.GET)
	@ResponseBody
	public Userspojo queryUsers(
			@CookieValue(value = "user", defaultValue = "") String id,
			HttpServletResponse response) {
		Userspojo result = ps.queryUsers(id);
		return result;
	}

	// 添加图片
	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@PathVariable String id,
			@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR_NO_FILE";
		}
		try {
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			List<Archivepojo> archive = ls.infol(id);
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload", archive
					.get(0).getArchive_id().toString(), newFileName);
			File existsFile = new File(filePath);
			if (!existsFile.getParentFile().exists()) {
				if (!existsFile.getParentFile().mkdirs()) {
					System.out.println("创建目录失败");
					return "ERROR_ON_MKDIR";
				}
			}
			if (existsFile.exists()) {
				if (existsFile.delete()) {
					System.out.println("删除原始文件：" + filePath);
				} else {
					System.out.println("删除文件失败：" + filePath);
				}
			}
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath)));
			stream.write(bytes);
			stream.close();
			fs.info(id, newFileName);
			return "OK";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
	}

	// 用户退出
	@RequestMapping(value = "/tuichu.action", method = RequestMethod.POST)
	@ResponseBody
	public String tuichu(
			@CookieValue(value = "user", defaultValue = "") String userId,
			HttpServletResponse response) {
		SqlSession sql = MySqlSessionFactory.getSqlSession();
		Users dao = sql.getMapper(Users.class);
		response.addCookie(new Cookie("user", null));
		return "OK";
	}

	// 显示图片
	@RequestMapping(value = "/query_file.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Filepojo> query_file(
			@RequestParam(value = "id", defaultValue = "") String id) {
		List<Filepojo> a = fs.query_file(id);
		return a;
	}

	// 模糊查询
	@RequestMapping(value = "/queryall.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map> queryall(
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "brithday", defaultValue = "") String brithday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		List<Map> map = ls.queryall(archive_id, identity, name, gender,
				brithday, date_retire1, date_retire2, sp, fc, title, seniority);
		return map;
	}

	// 查询最近添加的档案
	@RequestMapping(value = "/queryjin.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryjin(
			@RequestParam(value = "user_id", defaultValue = "") String user_id) {
		List<Map> map = ls.queryjin(user_id);
		return map;
	}

	// 查询最近浏览的档案
	@RequestMapping(value = "/queryliu.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryliu(
			@RequestParam(value = "user_id", defaultValue = "") String user_id) {
		List<Map> map = ls.queryliu(user_id);
		return map;
	}

	// 统计
	@RequestMapping(value = "/tongji.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> tongji() {
		List<Map> map = ps.tongji();
		return map;
	}

	// 显示将要删除的图片
	@RequestMapping(value = "/querydel.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Filepojo> querydel(
			@RequestParam(value = "id", defaultValue = "") String id) {
		List<Filepojo> filepojo = fs.querydel(id);
		return filepojo;
	}

	// 删除图片
	@RequestMapping(value = "/deletephoto.action", method = RequestMethod.POST)
	@ResponseBody
	public String deletephoto(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletRequest req) {
		List<Filepojo> filepojo = fs.querydel(id);
		String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
				.getServletContext().getRealPath("/"), "upload", filepojo
				.get(0).getArchive_id().toString(), filepojo.get(0).getName()
				.toString());
		File existsFile = new File(filePath);
		existsFile.delete();
		fs.deletephoto(id);
		return "OK";
	}

	// 查询时间段
	@RequestMapping(value = "/querytime.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map> querytime(
			@RequestParam(value = "begin", defaultValue = "") String begin,
			@RequestParam(value = "end", defaultValue = "") String end,
			HttpServletRequest response) {
		List<Map> map = ps.querytime(begin, end);
		return map;
	}
}
